using SimpleJSON;

namespace Gj
{
    public class SelectChildHelper : NodeHelper
    {
        public BindDataType dataType = BindDataType.Int;
        private JSONArray actionList;

        protected override BindDataType bindDataType => dataType;

        protected override void BindData(int i)
        {
            actionList = new JSONArray();
            if (i >= 0 && i < child.Count) actionList.Add(i);
            BindChild();
        }

        protected override void BindData(JSONArray array)
        {
            actionList = array;
            BindChild();
        }

        private void BindChild()
        {
            var helperIndex = 0;
            foreach (var helper in child)
            {
                helper.SetIndex(helperIndex);
                // helper.OnChange((int i, bool b) => { ChangeSelect(i, b); });
                helper.SetData(false);
                helperIndex++;
            }

            for (var i = 0; i < actionList.Count; i++)
            {
                var index = actionList[i].AsInt;
                if (child.Count > index)
                    child[index].SetData(true);
            }
        }

        private void ChangeSelect(int index, bool b)
        {
            if (dataType == BindDataType.Int)
            {
                if (b) Change(index);
            }
            else
            {
                var selectIndex = -1;
                for (var i = 0; i < actionList.Count; i++)
                    if (actionList[i].AsInt == index)
                        selectIndex = i;
                if (b) actionList.Add(index);
                if (!b) actionList.Remove(selectIndex);
                Change(actionList);
            }
        }
    }
}